package com.jsjosem.aftersales.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.databinding.ActivityRegisterAccountBinding;
import com.jsjosem.aftersales.request.VerifyCodeRequest;
import com.jsjosem.aftersales.utils.ImmUtils;

import java.util.Objects;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 注册界面
 */
public class RegisterAccountActivity extends AppCompatActivity {

    private final VerifyCodeRequest verifyCodeRequest = new VerifyCodeRequest();

    private CountDownTimer start;

    private String phone;

    private String password;

    private EditText registerPhoneEt, registerVerifyCodeEt, registerPasswordEt, registerPasswordConfirmEt;

    private ActivityRegisterAccountBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRegisterAccountBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
    }

    private void initView() {
        registerPhoneEt = findViewById(R.id.register_phone);
        registerVerifyCodeEt = findViewById(R.id.register_verify_code);
        registerPasswordEt = findViewById(R.id.register_password);
        registerPasswordConfirmEt = findViewById(R.id.register_password_confirm);

        ImmUtils.setEditTextHintFontSize(registerPhoneEt, 12,"请输入手机号");
        ImmUtils.setEditTextHintFontSize(registerVerifyCodeEt, 12,"请输入验证码");
        ImmUtils.setEditTextHintFontSize(registerPasswordEt, 12,"请输入密码");
        ImmUtils.setEditTextHintFontSize(registerPasswordConfirmEt, 12,"请确认密码");

        // 点击获取验证码
        clickGetVerifyCode();

        // 点击用户协议，跳转到用户服务协议界面
        clickUserAgreement();

        // 点击立即注册
        clickRegisterAccount();

        // 点击已有密码，立即登录
        TextView loginTv = findViewById(R.id.register_login);
        loginTv.setOnClickListener(view -> {
            // 回到登录页，直接关闭当前页面
            finish();
        });
    }

    private void clickRegisterAccount() {
        TextView immediatelyRegisterBt = findViewById(R.id.immediately_register_bt);
        immediatelyRegisterBt.setOnClickListener(view -> {
            // 表单字段校验
            if (validateForm()) {
                return;
            }

            // TODO 注册账号
            Toast.makeText(RegisterAccountActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
            // 注册成功，返回登录页
            finish();
        });
    }

    private boolean validateForm() {
        if (validatePhone()) {
            return true;
        }

        // 校验验证码是否输入
        EditText verifyCodeEt = findViewById(R.id.register_verify_code);
        Editable verifyCodeText = verifyCodeEt.getText();
        if (verifyCodeText.length() != 5) {
            verifyCodeEt.setError("请输入正确的验证码");
            return true;
        }

        EditText registerPasswordEt = findViewById(R.id.register_password);
        Editable registerPasswordText = registerPasswordEt.getText();
        if (registerPasswordText.length() < 6 || registerPasswordText.length() > 20) {
            registerPasswordEt.setError("请设置6~20位的密码");
            return true;
        }

        EditText registerPasswordConfirmEt = findViewById(R.id.register_password_confirm);
        Editable registerPasswordConfirmText = registerPasswordConfirmEt.getText();
        if (registerPasswordConfirmText.length() < 6 || registerPasswordConfirmText.length() > 20) {
            registerPasswordConfirmEt.setError("请设置6~20位的密码");
            return true;
        }

        String registerPasswordConfirmContent = registerPasswordConfirmText.toString();
        String registerPasswordContent = registerPasswordText.toString();
        if (!StrUtil.equals(registerPasswordContent, registerPasswordConfirmContent)) {
            registerPasswordConfirmEt.setError("两次输入的密码不一致");
            return true;
        }
        password = registerPasswordConfirmContent;

        CheckBox registerAgreeCb = findViewById(R.id.register_agree_cb);
        if (!registerAgreeCb.isChecked()) {
            String userAgreementText = getApplication().getString(R.string.register_user_agreement_text);
            String msg = "请同意" + userAgreementText + "后再进行注册";
            Toast.makeText(RegisterAccountActivity.this, msg, Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    private void clickUserAgreement() {
        TextView userAgreementTv = findViewById(R.id.register_user_agreement);
        userAgreementTv.setOnClickListener(view -> {
            Intent intent = new Intent(RegisterAccountActivity.this, UserAgreementActivity.class);
            startActivity(intent);
        });
    }

    private void clickGetVerifyCode() {
        TextView getVerifyCodeTv = findViewById(R.id.register_get_verify_code);
        getVerifyCodeTv.setOnClickListener(view -> {
            if (Objects.nonNull(start)) {
                return;
            }
            if (validatePhone()) {
                return;
            }
            // 发起发送验证码请求
            verifyCodeRequest.send(phone, (res) -> {
                // 发送成功，修改获取验证码的TextView，并且变成60秒倒计时
                start = new CountDownTimer(60000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        getVerifyCodeTv.setText(millisUntilFinished / 1000 + "秒后可重新获取");
                        getVerifyCodeTv.setTextColor(ContextCompat.getColor(RegisterAccountActivity.this, R.color.text_check_box_color));
                    }

                    public void onFinish() {
                        getVerifyCodeTv.setText(R.string.get_verify_code_text);
                        getVerifyCodeTv.setTextColor(ContextCompat.getColor(RegisterAccountActivity.this, R.color.text_view_color));
                    }
                }.start();
            }, failedMessage -> Toast.makeText(RegisterAccountActivity.this, failedMessage.toString(), Toast.LENGTH_SHORT).show());
        });
    }

    private boolean validatePhone() {
        EditText phoneEt = findViewById(R.id.register_phone);
        if (phoneEt.getText().length() <= 0) {
            phoneEt.setError("请输入手机号");
            return true;
        }
        phone = phoneEt.getText().toString();
        if (!PhoneUtil.isMobile(phone)) {
            phoneEt.setError("请输入正确的手机号");
            return true;
        }
        return false;
    }
}